import urllib.parse,http.client
import os
import xml.dom.minidom
artistName=''
path='.'
def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)
def handleImages(domXml,pathIn,artistNameIn):
    global path,artistName
    artistName=artistNameIn
    path=pathIn
    images = domXml.getElementsByTagName("image")
    for image in images:
        handleImage(image)
def handleImage(image):
    global artistName,path
    proimage=image.getElementsByTagName("size")[0]
    fileName=artistName+'_'+os.path.split(getText((image.getElementsByTagName("url")[0]).childNodes))[1]
    imageUrl=getText(proimage.childNodes)
    fileName=path+'\\'+fileName+os.path.splitext(imageUrl)[1]
    if not os.path.exists(fileName):
        print(imageUrl,fileName)
        imageUrl=httpLink(imageUrl)
        if imageUrl:
            f=open(fileName,'wb')
            f.write(imageUrl.read())
            f.close()
    else:
        print('exists')
def httpLink(url):
    headers={"user-agent":"Il0Vu"}
    conn=http.client.HTTPConnection('0-focus-opensocial.googleusercontent.com')
    #Use Google's Proxy, quicker in certain network 
    conn.request('GET',tranformUrl(url),"",headers)
    req=conn.getresponse()
    if req.reason.lower() == 'ok'  :
        return req
    else:
        print("download failed")
        print(req.reason,req.status)
        return False
def tranformUrl(url):
    return '/gadgets/proxy?url='+urllib.parse.quote(url)+'&container=focus&gadget=a&rewriteMime=image%2F*&refresh=31536000'
